package com.andy.wang.controller;

import com.andy.wang.pojo.Friend;
import com.andy.wang.pojo.Result;
import com.andy.wang.pojo.User;
import com.andy.wang.service.FriendService;
import com.andy.wang.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@CrossOrigin
public class HomeUserController {
    @Autowired
    private UserService userService;
    @Autowired
    private FriendService friendService;

    @GetMapping("/users")
    public Object getUsers(@RequestParam("uid") Long uid, @RequestParam("uhobbys") String uhobbys, @RequestParam("count") int count, @RequestParam("search") String search) {
        return Result.success(userService.QueryRecommendation(uid, uhobbys, count, search));
    }

    @GetMapping("/countNumber")
    public Object getUsers() {
        return Result.success(userService.QueryCountNumber());
    }

    // 查询是否有人发送好友申请
    @GetMapping("/apply")
    public Object newNews(@RequestParam("page")int page, @RequestParam("uid") Long uid) {
        return Result.success(friendService.getFriendAskList(page,uid));
    }

    // 查询当前用户有几条申请
    @GetMapping("/applyNumber")
    public Object newNews(@RequestParam("uid") Long uid) {
        LambdaQueryWrapper<Friend> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(Friend::getAccept,uid)
                .eq(Friend::getFriendStatus,0);
        return Result.success(friendService.count(lambdaQueryWrapper));
    }


    // 添加好友
    @PostMapping("/addFriend")
    public Object setFriend(@RequestBody Friend friend) {
        System.out.println(friend.toString());
        return Result.success(friendService.save(friend));
    }

    // 查看好友申请详情
    @GetMapping("/{uid}")
    public Object getFriendDetails(@PathVariable("uid") Long uid) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(User::getUid,uid);
        return Result.success(userService.list(lambdaQueryWrapper));
    }

    // 是否添加为好友
    @PutMapping("/{status}/{fid}")
    public Object updateFStatus(@PathVariable("status") int status,@PathVariable("fid") int fid){
        UpdateWrapper<Friend> updateWrapper = new UpdateWrapper();
        Timestamp timestamp = new Timestamp(new java.util.Date().getTime());    // 写入日期和时间
        updateWrapper.set("friendStatus",status)
                    .set(status==1,"friend.rank",1)
                    .set("friend.friendDateTime",timestamp)
                    .eq("fID",fid);
        return Result.success(friendService.update(updateWrapper));
    }


}
